package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageResult search(RequestParams params) {
        Integer page = params.getPage();
        Integer size = params.getSize();
        // 1. 创建搜索请求
        SearchRequest request = new SearchRequest("hotel");
        try {
            // 构建查询条件
            buildBasicQuery(request,params);
            // 设置分页参数
            request.source().from((page-1)*size);
            request.source().size(size);
            // 2. 客户端执行请求
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            return handleResponse(response);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("查询出现错误   {}",e.getMessage());
            return null;
        }
    }

    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        // 1. 创建搜索请求
        SearchRequest request = new SearchRequest("hotel");
        //     设置搜索条件
        buildBasicQuery(request,params);
        //      size 0
        request.source().size(0);
        //      指定  city 分组
        //      指定  starName 分组
        //      指定  brand 分组
        buildAggsRequest(request);
        // 2. 执行请求
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 3. 解析相应结果
            Aggregations aggregations = response.getAggregations();
            //     获取 city分组聚合结果
            List<String> cityList = handleAggsResult(aggregations, "city");
            //     获取 starName分组聚合结果
            List<String> starNameList = handleAggsResult(aggregations, "starName");
            //     获取 brand分组聚合结果
            List<String> brandList = handleAggsResult(aggregations, "brand");
            //     Map<String,List<String>>
            Map<String,List<String>> map = new HashMap<>();
            map.put("city",cityList);
            map.put("starName",starNameList);
            map.put("brand",brandList);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("服务出现异常，{}",e.getMessage());
            return null;
        }
    }

    @Override
    public List<String> suggestion(String key) {
        // 1. 创建搜索请求
        SearchRequest request = new SearchRequest("hotel");
        //    创建自动补全请求
        request.source().suggest(
                new SuggestBuilder()
                .addSuggestion("mySuggestion",
                        SuggestBuilders.completionSuggestion("suggestion")
                                       .prefix(key)
                                       .skipDuplicates(true)
                                       .size(10)
                ));
        // 2. 执行
        try {
            SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
            // 3. 解析响应
            Suggest suggest = response.getSuggest();
            // 查询自定义的结果
            CompletionSuggestion suggestion = suggest.getSuggestion("mySuggestion");
            // 获取结果中的options 并遍历  取出每个option的text
            List<String> list = new ArrayList<>();
            for (CompletionSuggestion.Entry.Option option : suggestion.getOptions()) {
                list.add(option.getText().toString());
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("自动提示查询失败, {}",e.getMessage());
        }
        return null;
    }

    @Override
    public void addDocument(Long id) {
        Hotel hotel = this.getById(id);
        HotelDoc hotelDoc = new HotelDoc(hotel);
        IndexRequest request = new IndexRequest("hotel");
        // 设置好数据
        request.id(hotel.getId() + "");
        request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
        // 执行请求
        try {
            restHighLevelClient.index(request, RequestOptions.DEFAULT);
            log.info("成功添加文档到索引库");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("添加文档出现异常，原因: {}",e.getMessage());
            throw new RuntimeException();
        }
    }
    @Override
    public void deleteDocument(Long id) {
        DeleteRequest request = new DeleteRequest("hotel",String.valueOf(id));
        try {
            restHighLevelClient.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("删除文档出现异常，原因: {}",e.getMessage());
            throw new RuntimeException();
        }
    }

    private List<String> handleAggsResult(Aggregations aggregations,String name){
        Terms result = aggregations.get(name);
        List<String> list = new ArrayList<>();
        List<? extends Terms.Bucket> buckets = result.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            list.add(bucket.getKeyAsString());
        }
        return list;
    }

    private void buildAggsRequest(SearchRequest request) {
        request.source().aggregation(AggregationBuilders.terms("city").field("city").size(20));
        request.source().aggregation(AggregationBuilders.terms("starName").field("starName").size(20));
        request.source().aggregation(AggregationBuilders.terms("brand").field("brand").size(20));
    }

    private void buildBasicQuery(SearchRequest request, RequestParams params) {
        String key = params.getKey();
        // 查询关键字条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(StringUtils.isBlank(key)){
            // 查询全部
            boolQuery.must(QueryBuilders.matchAllQuery());
        }else {
            // match 查询 all字段
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }
        // 查询城市
        String city = params.getCity();
        if (StringUtils.isNotBlank(city)) {
            boolQuery.filter(QueryBuilders.termQuery("city",city));
        }
        // 查询品牌
        String brand = params.getBrand();
        if (StringUtils.isNotBlank(brand)) {
            boolQuery.filter(QueryBuilders.termQuery("brand",brand));
        }
        // 查询星级
        String starName = params.getStarName();
        if (StringUtils.isNotBlank(starName)) {
            boolQuery.filter(QueryBuilders.termQuery("starName",starName));
        }

        // 查询价格范围
        Integer minPrice = params.getMinPrice();
        if (minPrice!=null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(minPrice));
        }
        Integer maxPrice = params.getMaxPrice();
        if (maxPrice!=null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").lt(maxPrice));
        }
        String location = params.getLocation();
        if (StringUtils.isNotBlank(location)) {
            request.source().sort( // 设置排序
                    SortBuilders.geoDistanceSort("location",new GeoPoint(location)) // 按照地理坐标 排序
                            .order(SortOrder.ASC)  // 升序
                            .unit(DistanceUnit.KILOMETERS)  // 距离单位 KM
            );
        }
        // 增加算分查询条件
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                boolQuery,  // 原始的查询条件
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                               QueryBuilders.termQuery("isAD",true),
                                ScoreFunctionBuilders.weightFactorFunction(5)
                        )
                }
        ).scoreMode(FunctionScoreQuery.ScoreMode.MULTIPLY);
        // 设置条件
        request.source().query(functionScoreQuery);
    }

    /**
     * 解析相应结果
     * @param response
     * @return
     */
    private PageResult handleResponse(SearchResponse response){
// 命中结果
        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;
        SearchHit[] docArr = hits.getHits();
        List<HotelDoc> list = new ArrayList<>();
        for (SearchHit doc : docArr) {

            HotelDoc hotelDoc = JSON.parseObject(doc.getSourceAsString(), HotelDoc.class);

            // 将排序的值  存入到distance字段中 用于前端页面显示距离
            Object[] sortValues = doc.getSortValues();
            if (sortValues!=null && sortValues.length > 0){
                hotelDoc.setDistance(sortValues[0]);
            }

            list.add(hotelDoc);
        }
        return new PageResult(total,list);
    }
}
